package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.ClasseMapper;
import com.indusfo.spc.mapper.ClasseWorkMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Classe;
import com.indusfo.spc.pojo.Productline;
import com.indusfo.spc.service.ClasseService;
import com.indusfo.spc.untlis.DateUtils;
import com.indusfo.spc.untlis.StringUtils;
import com.indusfo.spc.vo.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author louk
 * @date 2019/11/15 15:15
 */
@Service
public class ClasseServiceImpl implements ClasseService {

    @Resource
    private ClasseMapper classeMapper;
    @Resource
    private UploadMapper uploadMapper;

    @Resource
    private  ClasseWorkMapper classeWorkMapper;

    /**
     * 查询班次信息
     * @param classes
     * @return
     */
    @Override
    public JSONObject queryClasses(Classe classes) {


        Integer pagesize = classes.getPagesize();
        Integer pageindex = classes.getPageindex();
        if(pagesize != null && pageindex != null) {
            classes.setIncept(pagesize*(pageindex - 1));
        }
        List<Classe> classesList = classeMapper.queryClasses(classes);
        if(classesList.isEmpty()){
            return JSONObject.oK("没有相关数据", classesList, 0);
        }
        int i = classeMapper.countClasses(classes);
        return JSONObject.oK("查询成功", classesList,i);
    }

    /**
     * 更新班次信息
     * @param classes
     * @return
     */
    @Override
    public JSONObject updateClasses(Classe classes) {


        //更新时判断班次ID是否  判断班次名称是否为空并且重复  判断产线是否为空
        if(classes.getClasseId()==null){
            return JSONObject.build(500,"更新时请选择班次ID");
        }
        //判断所传时间格式是否正确
        String judgeResult = judge(classes);
        if(!StringUtils.isEmpty(judgeResult)){
            return JSONObject.build(JSONObject.ERROR,judgeResult);
        }
        int i = classeMapper.queryIsExist(classes);
        if(i>0){
            return JSONObject.build(500,"班次名称名称已存在");
        }
        String checkConflictResult = checkConflict(classes);
        if(!StringUtils.isEmpty(checkConflictResult)){
            return JSONObject.build(JSONObject.ERROR,checkConflictResult);
        }
        int row = classeMapper.updateClasses(classes);
        if(row == 0) {
            return JSONObject.build(500,"数据修改失败");

        }
        return JSONObject.oK("数据修改成功");
    }

    /**
     * 启用停用删除
     * @param classes
     * @param dataState
     * @return
     */
    @Override
    public JSONObject defineClasses(Integer[] classes, Integer dataState){

        //判断传入的参数是否为null
        if(dataState == null) {
            //为null抛出异常
            return JSONObject.build(500,"数据状态不能为空");
        }else if(dataState != 1 && dataState != 2 && dataState != 3) {
            return JSONObject.build(500,"数据状态错误");
        }
        if(classes == null || classes.length<=0) {
            return JSONObject.build(500,"请选择删除数据");
        }
        if(dataState==1){
            Classe classe = classeMapper.queryClassesByClasseId(classes[0]);
            String checkConflict = checkConflict(classe);
            if(!StringUtils.isEmpty(checkConflict)){
                return JSONObject.build(JSONObject.ERROR,checkConflict);
            }
        }
        if(new Integer(2).equals(dataState)){
            int useClasseWork = classeWorkMapper.queryUseClasse(classes);
            if(useClasseWork>0){
                return JSONObject.build(JSONObject.ERROR,"所选班次已开工,无法删除");
            }
        }
        //调用删除的接口
        int row = classeMapper.defineClasses(classes, dataState);
        //声明msg字符串，用来存抛出的异常
        String msg = "";
        if (row == 0) {
            // 判断传入的数据状态参数lDataState,返回相应信息
            switch (dataState) {
                case 1:
                    throw new ModifyFailedException("启用失败");
                case 2:
                    throw new ModifyFailedException("删除失败");
                case 3:
                    throw new ModifyFailedException("停用失败");
                default:
                    break;
            }
        } else {
            switch (dataState) {
                case 1:
                    msg = "启用成功";break;
                case 2:
                    msg = "删除成功";break;
                case 3:
                    msg = "停用成功";break;
                default:
                    break;
            }
        }
        return JSONObject.oK(msg);
    }

    /**
     * 新增班次信息
     * @param classes
     * @return
     */
    @Override
    public JSONObject insertClasses(Classe classes) {

        //新增时判断班次名称  以及工位是否为空
        if(classes.getClasseId()!=null){
            throw new ParamsErrorException("班次ID不能存在");
        }
        String judgeResult = judge(classes);
        if(!StringUtils.isEmpty(judgeResult)){
            return JSONObject.build(JSONObject.ERROR,judgeResult);
        }
        //新增时设置数据状态为1
        classes.setDataState(1);
        int i = classeMapper.queryIsExist(classes);
        if(i>0){
            return JSONObject.build(500,"名称已存在");
        }
        //判断当前与所属产线下的班次是否发生冲突
        String checkConflictResult = checkConflict(classes);
        if(!StringUtils.isEmpty(checkConflictResult)){
            return JSONObject.build(JSONObject.ERROR,checkConflictResult);
        }
        int row = classeMapper.insertClasses(classes);
        if(row == 0) {
            return JSONObject.build(500,"新增班次信息失败");
        }
        return JSONObject.oK("新增成功");
    }


    /**
     * 判断字段
     * @param classes
     */
    public String judge(Classe classes){

        if(classes.getClasseName().isEmpty()){
           return "班次名称不能为空";
        }
        if(classes.getProductlineId()==null){
            return "产线不能为空";
        }
        if(classes.getClasseName().getBytes().length>50){
            return "班次名称不能超过规定长度,长度50个字节,25个汉字";
        }
        try{
            if("".equals(classes.getStartDate())){
                classes.setDataState(null);
            }
            Date date = DateUtils.dateTime(DateUtils.HH_MM_SS, classes.getStartDate());
            classes.setStartDate(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, date));
        }catch (Exception e){
            return "班次信息开始时间格式不正确";
        }
        if(classes.getWorkHour()==null){
            return "工作时长不能为空";
        }
        Double workingHour = classes.getWorkHour();
        if(workingHour.toString().length()>10){
            return "工作时长数字过大";
        }
        if(workingHour>24){
            return "工作时长不能大于24";
        }
        return null;

    }

    /**
     * 检查excel中每个字段
     * @param classes
     * @return
     */
    @Override
    public String checkNoRepeatExcel(Classe classes) {
        if(StringUtils.isBlank(classes.getClasseName()) && StringUtils.isBlank(classes.getProductlineName()) && StringUtils.isBlank(classes.getStartDate()) && classes.getWorkHour()==null){
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if(StringUtils.isBlank(classes.getClasseName())){
            return "班次名称为空";
        }
        if(classes.getClasseName().getBytes().length>50){
            return "班次名称不能超过规定长度,长度50个字节,25个汉字";
        }
        if(classes.getProductlineName()==null){
            return "产线名称为空";
        }
        Map<String, Productline> productLineMap = uploadMapper.queryProductionLine();
        if(!productLineMap.containsKey(classes.getProductlineName())){
            return "产线名称输入错误/不规范";
        }
        if(StringUtils.isEmpty(classes.getStartDate())){
            return "开始时间为空/格式错误";
        }
        if(classes.getWorkHour()==null || "".equals(classes.getWorkHour())){
            return "工作时长不能为空";
        }
        classes.setProductlineId(productLineMap.get(classes.getProductlineName()).getProductlineId());
        try{
            Date parse = new SimpleDateFormat("hh:MM:ss").parse( classes.getStartDate() );
        }catch (Exception e){
//            classes.setStartDate("00:00:00");
            return "班次信息开始时间格式不正确";
        }
        int i = classeMapper.queryIsExist(classes);
        if(i>0){
            return "班次名称已存在";
        }
        if(classes.getWorkHour()!=null){
            Double workingHour = classes.getWorkHour();
            if(workingHour.toString().length()>10){
                return "工作时长数字不能大于10位数,并且小数点保留不能超过7位";
            }
        }
        String checkConflict = checkConflict(classes);
        if(!StringUtils.isEmpty(checkConflict)){
            return checkConflict;
        }
        return null;
    }

    /**
     * 批量新增班次信息
     * @param classesList
     * @return
     */
    @Override
    public JSONObject updateListClasses(List<Classe> classesList) {

        int flag = uploadMapper.updateListClasses(classesList);
        if(flag>0){
            return JSONObject.oK("新增成功");
        }
        return JSONObject.oK("新增失败");
    }

    /**
     * 判断新增,编辑,启用的班次信息是否与所属产线的班次信息发生冲突
     * @param classe
     * @return
     */
    public String checkConflict(Classe classe){
            //判断当前与所属产线下的班次是否发生冲突
        classe.setEndDate(DateUtils.getSimpleWorkhour(classe.getStartDate(),classe.getWorkHour()));
        List<Classe> classeList= classeMapper.queryListByProductline(classe);
        for (Classe queryClasse1 : classeList) {
            queryClasse1.setEndDate(DateUtils.getSimpleWorkhour(queryClasse1.getStartDate(),queryClasse1.getWorkHour()));
        }
        for (Classe queryClasse2 : classeList) {
            int startDateCompare1 = DateUtils.compareDate(queryClasse2.getStartDate(), classe.getStartDate());
            int startDateCompare2 = DateUtils.compareDate(queryClasse2.getEndDate(), classe.getStartDate());
            int endDateCompare1 = DateUtils.compareDate(queryClasse2.getStartDate(), classe.getEndDate());
            int endDateCompare2 = DateUtils.compareDate(queryClasse2.getEndDate(), classe.getEndDate());
            if((startDateCompare1<=0 && startDateCompare2>0 && endDateCompare1<0  && endDateCompare2>=0) ||
                (startDateCompare1>0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2>=0) ||
                (startDateCompare1<0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2<0) ||
                (startDateCompare1>=0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2<=0) ||
                (startDateCompare1<0 && startDateCompare2>0 && endDateCompare1<0  && endDateCompare2<=0) ||
                (startDateCompare1>=0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2>0)
            ){
                return "班次信息与所属产线下的其他班次发生冲突";
            }

        }
        return null;
    }


}
